﻿using System;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using internal_website.Models;
using log4net;

namespace internal_website.App_Data
{
    public class OrchestraSiteManagerDbInitializer : DropCreateDatabaseAlways<OrchestraSiteManagerContext>
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(OrchestraSiteManagerDbInitializer));

        protected override void Seed(OrchestraSiteManagerContext context)
        {
            
            var ds = new DefaultData();

            ds.Composers.ForEach(composer => context.Composers.Add(composer));
            foreach (var eventType in ds.EventTypes)
            {
                context.EventTypes.Add(eventType);
            }
            ds.CompositionGenres.ForEach(compositionGenre => context.CompositionGenres.Add(compositionGenre));

            foreach (var instrument in ds.Instruments)
            {
                context.Instruments.Add(instrument);
            }
            foreach (var location in ds.Locations)
            {
                context.Locations.Add(location);
            }
            foreach (var user in ds.Users)
            {
                context.Users.Add(user);
            }

            ds.InstrumentTypes.ForEach(instrumentType => context.InstrumentTypes.Add(instrumentType));

            try
            {

                context.SaveChanges();
            }
            catch (DbEntityValidationException validationEntityException)
            {
                foreach (var validationErrors in validationEntityException.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        log.Fatal(new {validationError.PropertyName, validationError.ErrorMessage});
                    }
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }
    }
}